package com.ruiboyun.liveapp.util.tool;


import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;


import com.ruiboyun.liveapp.base.App;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Created by pz on 2015/10/10.
 */
public class FileUtils {
    public static final String DB_CACHE = "db";
    public static final String DB_DIR = "db";
    public static final String DB_NAME = "dafenci.db";
    public static final int DB_VERSION = 1;
    public static final String ROOT_CACHE = "com.yihuan.archeryplus";
    public static final String HTML_CACHE = "html";
    public static final String VIDEO_CACHE = "video";
    public static final String RADIO_CACHE = "radio";
    public static final String IMAGE_CACHE = "image";

    //获取根目录
    public static String getRootCache() {
        File externalCacheDir = App.getInstance().getExternalCacheDir();
        if (!externalCacheDir.exists()) {
            //使用makedirs() 可以建立不只一层的directory,
            //用makedirs建立c:\\aa\\bb\\cc
            //若aa, bb不存在, makedirs会完整建立出所有的path!!
            externalCacheDir.mkdirs();
        }
        return externalCacheDir.getAbsolutePath();
    }

    /*
    * 获取图片的存储路径
    * */
    public static File getImageCache() {
        String imageCache = getRootCache() + File.separator + IMAGE_CACHE;
        File file = new File(imageCache);
        if (!file.exists()) {
            //使用makedir() 可以建立一层的directory,
            //利用makedir()建立c:\\aa\\bb\\cc
            //若aa, bb不存在, 则makedir会失败
            file.mkdir();
        }
        return file;
    }
    public static Uri getUri(Context context,File file) {
        Uri uri = null;
        if (Build.VERSION.SDK_INT < 24) {
            return Uri.fromFile(file);
        } else {
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            return uri;
        }

    }

    public static final File getImageFile(Context context, String fileName) {
        File img = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File rootDir = new File(Environment.getExternalStorageDirectory() + File.separator + ROOT_CACHE + "/image");
            if (!rootDir.exists()) {
                rootDir.mkdirs();
            }
            img = new File(rootDir.getAbsolutePath(), fileName);
        }else {
            Loger.e("存储不够");
        }
        return img;
    }
    public static File getRootFile(){
        File rootDir = new File(Environment.getExternalStorageDirectory() + File.separator + ROOT_CACHE );
        if (!rootDir.exists()) {
            rootDir.mkdirs();
        }
        return rootDir;
    }
    public static final File getApkFile(Context context, String fileName) {
        File img = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File rootDir = new File(Environment.getExternalStorageDirectory() + File.separator + ROOT_CACHE + "/apk");
            if (!rootDir.exists()) {
                rootDir.mkdirs();
            }
            img = new File(rootDir.getAbsolutePath(), fileName);
        }
        return img;
    }

    public static final String getObjectFile(Context context, String fileName) {
        File img = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File rootDir = new File(Environment.getExternalStorageDirectory() + File.separator + ROOT_CACHE + "/object");
            if (!rootDir.exists()) {
                rootDir.mkdirs();
            }
            img = new File(rootDir.getAbsolutePath(), fileName);
        }
        return img.getAbsolutePath();
    }

    /**
     * 文件转化为Object
     *
     * @param fileName
     * @return byte[]
     */
    public static Object file2Object(String fileName) {

        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(fileName);
            ois = new ObjectInputStream(fis);
            Object object = ois.readObject();
            return object;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 把Object输出到文件
     *
     * @param obj
     * @param outputFile
     */
    public static void object2File(Object obj, String outputFile) {
        ObjectOutputStream oos = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(outputFile));
            oos = new ObjectOutputStream(fos);
            oos.writeObject(obj);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }
    }

    //保存图片 并且生成图片uri
    public static File saveImage(Context context, Bitmap bitmap, String name) {
        File file = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            try {
                 file = FileUtils.getImageFile(context, name);
                FileOutputStream fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
                return file;
            } catch (Exception e) {
                e.printStackTrace();
                Loger.e(""+e.toString());
                return null;
            }
        }
        return file;
    }

    public static File getRootCache(Context context) {
        File rootFile = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
            rootFile = context.getExternalCacheDir();
        } else {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                rootFile = new File(Environment.getExternalStorageDirectory() + File.separator + ROOT_CACHE);
            } else {
                rootFile = new File(Environment.getDataDirectory() + File.separator + context.getPackageName());
            }
            if (!rootFile.exists()) {
                rootFile.mkdirs();
            }
        }
        return rootFile;
    }

    //sdk/dafenci/imageCache
    public static String getSaveBitmapPath(Context context) {
        String imagePath = getRootCache(context) + File.separator + IMAGE_CACHE;
        if (!new File(imagePath).exists()) {
            boolean mkdirs = new File(imagePath).mkdirs();
        }
        return imagePath;
    }

    /**
     * 获取数据库路径
     *
     * @param context
     * @return
     */
    public static String getDBPath(Context context) {
        String dbPath = getRootCache(context) + File.separator + DB_CACHE;
        if (!new File(dbPath).exists()) {
            boolean mkdirs = new File(dbPath).mkdirs();
        }

        return dbPath;
    }


    public static File getDbFile(Context context) {
        String dbPath = getRootCache(context) + File.separator + DB_DIR;
        File dbFile = new File(dbPath);
        if (!dbFile.exists()) {
            dbFile.mkdir();
        }
        return dbFile;
    }

    public static String videoUriToFile(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Video.VideoColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Video.VideoColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public static String audioUriToFile(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Audio.AudioColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public static String imageUriToFile(final Context context, final Uri uri) {

        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
    public static String imageUriToFiles(Context context,Uri selectedVideoUri) {
        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};

        Cursor cursor = context.getContentResolver().query(selectedVideoUri, filePathColumn, null, null, null);
//      也可用下面的方法拿到cursor
//      Cursor cursor = this.context.managedQuery(selectedVideoUri, filePathColumn, null, null, null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }
    public static final File getVideoFile(Context context, String fileName) {
        File img = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File rootDir = new File(Environment.getExternalStorageDirectory() + File.separator + context.getPackageName() + "/video");
            if (!rootDir.exists()) {
                rootDir.mkdirs();
            }
            img = new File(rootDir.getAbsolutePath(), fileName);
        }
        return img;
    }

}
